@echo off
setlocal enableextensions

echo Starting FTP Server Demo...
echo.

REM Set UTF-8 code page
chcp 65001 >nul 2>&1

REM Project root directory
set "BASE_DIR=%~dp0"
cd /d "%BASE_DIR%"
if %ERRORLEVEL% NEQ 0 (
    echo ERROR: Cannot change to project directory
    pause
    exit /b 1
)

REM Check main.py exists
if not exist "main.py" (
    echo ERROR: main.py not found
    pause
    exit /b 1
)

REM Create logs directory
set "LOG_DIR=%BASE_DIR%logs"
if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"

REM Set server config
set "APP_HOST=0.0.0.0"
set "APP_PORT=8000"

REM Python paths
set "VENV_PY=%BASE_DIR%env\Scripts\python.exe"
set "VENV_PIP=%BASE_DIR%env\Scripts\pip.exe"
set "EMBED_DIR=%BASE_DIR%python_embed"
set "EMBED_EXE=%EMBED_DIR%\python.exe"
set "EMBED_ZIP=%BASE_DIR%python_embed.zip"

set "PY_EXE="
set "PIP_EXE="

REM 1) Try existing virtual environment
echo INFO: Checking virtual environment...
if exist "%VENV_PY%" (
  "%VENV_PY%" --version >nul 2>&1
  if %ERRORLEVEL% EQU 0 (
    set "PY_EXE=%VENV_PY%"
    set "PIP_EXE=%VENV_PIP%"
    set "VENV_HOME="
    if exist "%BASE_DIR%env\pyvenv.cfg" (
      for /f "tokens=1,* delims== " %%A in ('findstr /b /c:"home =" "%BASE_DIR%env\pyvenv.cfg"') do set "VENV_HOME=%%B"
      if not "%VENV_HOME%"=="" (
        if not exist "%VENV_HOME%\python.exe" (
          echo WARN: Virtual environment base Python missing: %VENV_HOME%
          echo INFO: Removing invalid virtual environment...
rmdir /s /q "%BASE_DIR%env" >nul 2>&1
if exist "%BASE_DIR%env" powershell -nologo -noprofile -command "Remove-Item -Recurse -Force '%BASE_DIR%env'"
echo INFO: Rebuilding virtual environment...
set "PY_EXE="
set "PIP_EXE="
goto :TRY_SYSTEM_PY
        ) else (
          "%VENV_PY%" -m pip --version >nul 2>&1
           if %ERRORLEVEL% NEQ 0 (
             echo WARN: pip not available in virtual environment, rebuilding...
             rmdir /s /q "%BASE_DIR%env" >nul 2>&1
             if exist "%BASE_DIR%env" powershell -nologo -noprofile -command "Remove-Item -Recurse -Force '%BASE_DIR%env'"
             set "PY_EXE="
             set "PIP_EXE="
             goto :TRY_SYSTEM_PY
           ) else (
             "%VENV_PY%" -c "import sys; sys.exit(0 if sys.version_info[0]==3 and sys.version_info[1]==10 else 1)" >nul 2>&1
             if %ERRORLEVEL% NEQ 0 (
               echo WARN: Virtual environment Python version is not 3.10, rebuilding...
               rmdir /s /q "%BASE_DIR%env" >nul 2>&1
               if exist "%BASE_DIR%env" powershell -nologo -noprofile -command "Remove-Item -Recurse -Force '%BASE_DIR%env'"
               set "PY_EXE="
               set "PIP_EXE="
               goto :TRY_SYSTEM_PY
             ) else (
               echo INFO: Using existing virtual environment (Python 3.10)
             )
           )
        )
      ) else (
        echo INFO: Using existing virtual environment
      )
    ) else (
      echo INFO: Using existing virtual environment
    )
  ) else (
    echo WARN: Virtual environment corrupted
  )
) else (
  echo INFO: No virtual environment found
)

REM 2) Try embedded Python
if "%PY_EXE%"=="" (
  if not exist "%EMBED_EXE%" (
    if exist "%EMBED_ZIP%" (
      echo INFO: Extracting embedded Python...
      powershell -nologo -noprofile -command "Expand-Archive -Path '%EMBED_ZIP%' -DestinationPath '%EMBED_DIR%' -Force"
      if %ERRORLEVEL% NEQ 0 (
        echo ERROR: Failed to extract embedded Python
        pause
        exit /b 1
      )
      echo INFO: Embedded Python extracted
    ) else (
      echo INFO: No embedded Python found, trying system Python
      goto :TRY_SYSTEM_PY
    )
  ) else (
    echo INFO: Using existing embedded Python
  )
  set "PY_EXE=%EMBED_EXE%"
  set "PIP_EXE="
  "%EMBED_EXE%" -c "import sys; sys.exit(0 if sys.version_info[0]==3 and sys.version_info[1]==10 else 1)" >nul 2>&1
  if %ERRORLEVEL% NEQ 0 (
    echo WARN: Embedded Python is not 3.10. Please replace python_embed.zip with Python 3.10 embeddable package.
    set "PY_EXE="
    set "PIP_EXE="
    goto :TRY_SYSTEM_PY
  )
)

REM 3) Try system Python
if "%PY_EXE%"=="" (
  :TRY_SYSTEM_PY
  echo INFO: Trying system Python...
  where py >nul 2>&1
  if %ERRORLEVEL% EQU 0 (
    echo INFO: Creating virtual environment with py launcher (prefer 3.10)...
    py -3.10 -m venv env
    if %ERRORLEVEL% NEQ 0 (
      echo WARN: py -3.10 not available, falling back to py -3...
      py -3 -m venv env
      if %ERRORLEVEL% NEQ 0 (
        echo ERROR: Failed to create virtual environment
        pause
        exit /b 1
      )
    )
  ) else (
    where python >nul 2>&1
    if %ERRORLEVEL% EQU 0 (
      echo INFO: Creating virtual environment with python command...
      python -m venv env
      if %ERRORLEVEL% NEQ 0 (
        echo ERROR: Failed to create virtual environment
        pause
        exit /b 1
      )
    ) else (
      echo.
      echo ERROR: No Python environment found!
      echo Please ensure one of the following:
      echo 1. Complete env\ virtual environment directory
      echo 2. python_embed.zip embedded Python file
      echo 3. System Python 3.10+ installation
      echo.
      pause
      exit /b 1
    )
  )
  set "PY_EXE=%BASE_DIR%env\Scripts\python.exe"
  set "PIP_EXE=%BASE_DIR%env\Scripts\pip.exe"
  "%PY_EXE%" -c "import sys; sys.exit(0 if sys.version_info[0]==3 and sys.version_info[1]==10 else 1)" >nul 2>&1
  if %ERRORLEVEL% NEQ 0 (
    echo ERROR: Created virtual environment is not Python 3.10. Please install Python 3.10 or provide python_embed.zip (3.10).
    pause
    exit /b 1
  )
  echo INFO: Installing dependencies...
  "%PY_EXE%" -m pip install -r requirements.txt
  if %ERRORLEVEL% NEQ 0 (
    echo ERROR: Failed to install dependencies
    pause
    exit /b 1
  )
)

REM Check dependencies
echo INFO: Checking dependencies...
"%PY_EXE%" -c "import uvicorn" >nul 2>&1
if %ERRORLEVEL% NEQ 0 (
  if not "%PIP_EXE%"=="" (
    echo INFO: Installing missing dependencies...
    "%PY_EXE%" -m pip install -r requirements.txt
    if %ERRORLEVEL% NEQ 0 (
      echo ERROR: Failed to install dependencies
      pause
      exit /b 1
    )
  ) else (
    echo ERROR: Missing uvicorn dependency and cannot auto-install
    echo Please install dependencies manually
    pause
    exit /b 1
  )
)

REM Check port availability
echo INFO: Checking port availability...
netstat -ano | findstr ":8000" | findstr LISTENING >nul 2>&1
if not errorlevel 1 (
  echo WARN: Port 8000 is occupied, switching to 8001
  set "APP_PORT=8001"
  netstat -ano | findstr ":8001" | findstr LISTENING >nul 2>&1
  if not errorlevel 1 (
    echo WARN: Port 8001 is occupied, switching to 8002
    set "APP_PORT=8002"
  )
) else (
  set "APP_PORT=8000"
)
echo INFO: Using port %APP_PORT%

REM Start management backend
echo INFO: Starting management backend...
set "UVICORN_ARGS="
if exist "logging_config.json" (
  set "UVICORN_ARGS=--log-config logging_config.json"
)
start "" "%PY_EXE%" -m uvicorn main:app --host %APP_HOST% --port %APP_PORT% %UVICORN_ARGS%

REM Wait for service to start
echo INFO: Waiting for service to start...
powershell -nologo -noprofile -command "for ($i=0;$i -lt 40;$i++) { try { Invoke-RestMethod -Uri ('http://127.0.0.1:%APP_PORT%/api/status') -TimeoutSec 2 | Out-Null; exit 0 } catch {}; Start-Sleep -Milliseconds 500 }; exit 1" >nul 2>&1
if %ERRORLEVEL% NEQ 0 (
  echo ERROR: Management backend failed to start
  echo INFO: No error log available
  pause
  exit /b 1
)

REM Auto-start FTP service
echo INFO: Auto-starting FTP service...
powershell -nologo -noprofile -command "try { $body=@{host='0.0.0.0';port=2121} | ConvertTo-Json; Invoke-RestMethod -Method Post -Uri 'http://127.0.0.1:%APP_PORT%/api/server/start' -ContentType 'application/json' -Body $body | Out-Null; exit 0 } catch { exit 1 }"
if %ERRORLEVEL% NEQ 0 (
  echo WARN: FTP service auto-start failed, please start manually from web interface
) else (
  echo INFO: FTP service started on port 2121
)

echo.
echo ========================================
echo SUCCESS: Startup completed!
echo ========================================
echo INFO: Management interface: http://127.0.0.1:%APP_PORT%/
echo INFO: Opening web interface...
echo.

start "" "http://127.0.0.1:%APP_PORT%/"
endlocal